package com.xdh.zzqh.ui


import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.core.view.size
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.xdh.zzqh.R
import com.xdh.zzqh.store.ExcelInfo
import com.xdh.zzqh.store.Product
import com.xdh.zzqh.store.User
import com.xdh.zzqh.store.productWithRow
import com.xdh.zzqh.store.userWithRow
import com.xdh.zzqh.ui.fragment.OrderFragment
import com.xdh.zzqh.ui.fragment.ProductFragment
import com.xdh.zzqh.ui.fragment.UserFragment
import com.xdh.zzqh.utils.initAll
import com.xdh.zzqh.utils.runOnUiWithInit
import com.xdh.zzqh.utils.runWithDb
import com.xdh.zzqh.utils.showToast
import com.xdh.zzqh.utils.stringById
import org.apache.poi.hssf.usermodel.HSSFWorkbook
import org.apache.poi.ss.usermodel.WorkbookFactory


class MainActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if ((intent.action == Intent.ACTION_VIEW) && (intent.data != null)) {
            openXls(intent.data!!)
        } else {
            TabInit(this)
        }
    }

    private fun openXls(uri: Uri) {
        runOnUiWithInit {
            try {
                val info = handleExcel(uri)
                for (product in info.products) {
                    product.saveOnDelete()
                }

                for (user in info.users) {
                    User(user).saveOnNotExists()
                }
                showToast(stringById(R.string.dao_ru_cheng_gong))
            } catch (e: Exception) {
                e.printStackTrace()
                showToast(e.message ?: stringById(R.string.cuo_wu))
            }
            TabInit(this)
        }
    }

    private suspend fun handleExcel(uri: Uri) = runWithDb {

        Log.d("DEBUG", "openXls: $uri")

        val input = contentResolver.openInputStream(uri)
        input.use {
            val ps = ArrayList<Product>()
            val us = ArrayList<String>()

            val name = uri.toString()
            if (name.endsWith("xls")) {
                val workbook = HSSFWorkbook(input)
                val productSheet = workbook.getSheetAt(0)
                val userSheet = workbook.getSheetAt(1)
                workbook.creationHelper.createFormulaEvaluator().evaluateAll()
                Log.d("DEBUG", "handleExcel: ${productSheet.lastRowNum} ${productSheet.physicalNumberOfRows}")
                for (index in 1 .. productSheet.lastRowNum) {
                    val row = productSheet.getRow(index) ?: continue
                    Log.d("DEBUG", "handleExcel: $index")
                    val product = productWithRow(row)
                    if (product != null) {
                        ps.add(product)
                    }
                }
                for (index in 1 .. userSheet.lastRowNum) {
                    val row = userSheet.getRow(index) ?: continue
                    val user = userWithRow(row)
                    if (user != null) {
                        us.add(user)
                    }
                }

            } else if (name.endsWith("xlsx")) {
                val workbook = WorkbookFactory.create(input)
                val productSheet = workbook.getSheetAt(0)
                val userSheet = workbook.getSheetAt(1)
                workbook.creationHelper.createFormulaEvaluator().evaluateAll()

                for (index in 1 .. productSheet.lastRowNum) {
                    val row = productSheet.getRow(index) ?: continue
                    val product = productWithRow(row)
                    if (product != null) {
                        ps.add(product)
                    }
                }
                for (index in 1 .. userSheet.lastRowNum) {
                    val row = userSheet.getRow(index) ?: continue
                    val user = userWithRow(row)
                    if (user != null) {
                        us.add(user)
                    }
                }
            }

            ExcelInfo(ps, us)
        }

    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus) {
            initAll()
        }
    }
}


private class TabInfo(
    val text: String,
    val iconId: Int,
    val fragment: Fragment
)

private class TabInit(activity: MainActivity) : FragmentStateAdapter(activity) {

    private val tabInfos = arrayOf(
        TabInfo(stringById(R.string.kai_dan), R.drawable.ic_setting, OrderFragment()),
        TabInfo(stringById(R.string.chan_pin), R.drawable.ic_setting, ProductFragment()),
        TabInfo(stringById(R.string.ke_hu), R.drawable.ic_setting, UserFragment()),
    )

    init {
        val vp2 = activity.findViewById<ViewPager2>(R.id.id_main_vp2)
        val tabs = activity.findViewById<TabLayout>(R.id.id_main_tab_layout)

        vp2.adapter = this
        vp2.offscreenPageLimit = tabs.size
        TabLayoutMediator(tabs, vp2, true, true) { tab, index ->
            tab.text = tabInfos[index].text
            tab.setIcon(tabInfos[index].iconId)
        }.attach()
    }

    override fun getItemCount(): Int {
        return tabInfos.size
    }

    override fun createFragment(position: Int): Fragment {
        return tabInfos[position].fragment
    }
}


